//
// JDBCMetaInfoJig
//

package net.fauxjobuilder.jig;

import java.sql.*;
import java.util.*;
import net.jextra.dbconnection.*;
import net.jextra.jig.*;

@JigDef( description="Run the builder to extra schema from database." )
public class JDBCMetaInfoJig implements Jig
{
    // ============================================================
    // Fields
    // ============================================================

    @JigField( "ConnDef:" )
    private String _connDef;

    @JigField( "Database Schema:" )
    private String _dbSchema;

    // ============================================================
    // Methods
    // ============================================================

    // ----------
    // public
    // ----------

    @JigCommand( "Execute" )
    public void execute()
        throws Exception
    {
        Connection connection = DB.getConnection( _connDef );
        DatabaseMetaData data = connection.getMetaData();

        ResultSet tableRS = data.getTables( null, _dbSchema, null, new String[]
        {
            "TABLE"
        } );

        while ( tableRS.next() )
        {
            getTableInfo( data, tableRS.getString( "TABLE_NAME" ) );
        }
        tableRS.close();
    }

    // ----------
    // private
    // ----------

    public void getTableInfo( DatabaseMetaData data, String tableName )
        throws Exception
    {
        System.out.println( "==== " + tableName + " ====" );
        //
        // Collect key columns
        //
        HashSet<String> keyColumns = new HashSet<String>();
        ResultSet rs = data.getPrimaryKeys( null, null, tableName );
        while ( rs.next() )
        {
            keyColumns.add( rs.getString( "COLUMN_NAME" ).toLowerCase() );
        }
        rs.close();

        //
        // Collect field definitions.
        //
        rs = data.getColumns( null, null, tableName, null );
        while ( rs.next() )
        {
            System.out.println( ( keyColumns.contains( rs.getString(
                "COLUMN_NAME" ).toLowerCase() ) ? "*" : " " ) + " " +
                rs.getString( "COLUMN_NAME" ) + " " + rs.getInt( "DATA_TYPE" ) + " " +
                rs.getInt( "NULLABLE" ) );
        }
        rs.close();

        //
        // Collect FK definitions.
        //
//        rs = data.getImportedKeys( null, null, table.getRawName() );
//        while ( rs.next() )
//        {
//            ForeignKey fk = new ForeignKey( rs.getString( "FKCOLUMN_NAME" ),
//                rs.getString( "PKTABLE_NAME" ), rs.getString( "PKCOLUMN_NAME" ) );
//        }
//        rs.close();
    }
}

